const {executeQuery} = require('../config/db_config')
const express = require('express')

let categoryRouter = express.Router()
categoryRouter.use(express.json())
/**
 * 获取所有种类
 */
categoryRouter.get("/",async (req,resp)=>{
   const sql = `select * from category`
  const res = await executeQuery(sql)
  resp.send({
    code:200,
    msg:'success',
    data:res
  })
})

/**
 * 添加种类
 */
categoryRouter.post("/",async (req,resp)=>{
  const sql = `insert into  category(text) values('${req.body.data.name}')`
 const res = await executeQuery(sql)
 resp.send({
   code:200,
   msg:'success',
   data:res
 })
})

/**
 * 删除指定id的种类
 */
categoryRouter.delete("/",async (req,resp)=>{
  const sql = `delete from  category where id=${req.query.id}`
 const res = await executeQuery(sql)
 resp.send({
   code:200,
   msg:'success',
   data:res
 })
})

/**
 * 分页获取所有种类
 */
categoryRouter.get("/page",async (req,resp)=>{
  const limit = req.query.limit
  const startIndex = (req.query.now_page-1)*limit
  const sql = `select * from category limit ${startIndex},${limit}`
  const sql1 = `select count(*) as num from category `
 const res = await executeQuery(sql)
 const res1 = await executeQuery(sql1)
 resp.send({
   code:200,
   msg:'success',
   data:{
    total:res1[0]?.num,
    list:res
  }
 })
})

module.exports={
  categoryRouter
}